package com.itsu.spbspider.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itsu.spbspider.entity.source.ParamsWeather;
import com.itsu.spbspider.mapper.CrawlerMapper;
import com.itsu.spbspider.service.Crawler;
import com.itsu.spbspider.util.HttpUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author suben
 * @create time 2020/2/10 19:23
 */
@Service(value = "baiduWeatherCrawler")
public class BaiduWeatherCrawler implements Crawler {

    @Resource
    private CrawlerMapper crawlerMapper;

    @Override
    public String crawlerData(Integer crawlId) throws Exception {
        com.itsu.spbspider.entity.Crawler crawler = crawlerMapper.selectById(crawlId);
        Map<String, String> params = this.initHeadersParams(crawler.getParams());
        Map<String, String> headers = this.initHeadersParams(crawler.getHeaders());
        String content = null;
        if ("GET".equals(crawler.getMethod().toUpperCase())) {
            content = HttpUtil.get(crawler.getUrl(), params, headers);
        } else {
            content = HttpUtil.post(crawler.getUrl(), params, headers);
        }
        return content;
    }

    protected Map<String, String> initHeadersParams(String content) throws IllegalAccessException {
        JSONObject jsonObject = JSON.parseObject(content);
        ParamsWeather paramsWeather = jsonObject.toJavaObject(ParamsWeather.class);
        Map<String, String> ret = new LinkedHashMap<>();
        if (paramsWeather == null) {
            return ret;
        }

        Field[] fields = paramsWeather.getClass().getDeclaredFields();
        List<Field> fieldList = Arrays.stream(fields).filter(x -> {
            x.setAccessible(true);
            return true;
        }).collect(Collectors.toList());

        for (Field field : fieldList) {
            Object value = field.get(paramsWeather);
            if (value != null) {
                ret.put(field.getName(), value.toString());
            }
        }

        return ret;
    }
}
